package com.yjq.blog.advice;

import com.alibaba.fastjson.JSONObject;
import com.yjq.blog.annotation.IgnoreResponse;
import com.yjq.blog.vo.HostInfo;
import com.yjq.blog.vo.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.Host;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@Slf4j
@RestControllerAdvice(basePackages = "com.yjq.blog")
public class CommonResponseDataAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter,
                            Class<? extends HttpMessageConverter<?>> aClass) {

        if (methodParameter.getDeclaringClass().isAnnotationPresent(
                IgnoreResponse.class
        )) {
            return false;
        }

        if (methodParameter.getMethod().isAnnotationPresent(
                IgnoreResponse.class
        )) {
            return false;
        }

        return true;
    }

    @Nullable
    @Override
    public Object beforeBodyWrite(@Nullable Object o,
                                  MethodParameter methodParameter,
                                  MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> aClass,
                                  ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {

        HostInfo hostInfo = new HostInfo(serverHttpRequest.getLocalAddress().getAddress().getHostAddress(), serverHttpRequest.getLocalAddress().getHostName());
        if (o instanceof Response) {
            ((Response) o).setHostInfo(hostInfo);
            return o;
        } else if (o instanceof String) {
            return JSONObject.toJSONString(Response.success(o).setHostInfo(hostInfo));
        } else {
            return Response.success(o).setHostInfo(hostInfo);
        }

    }
}
